/**
 * CategoryManager - 分组管理器
 * 负责分组的增删改查、渲染等功能
 */

class CategoryManager {
    // 常量定义
    static CONSTANTS = {
        DEFAULT_COLOR: '#667eea',
        DEFAULT_ICON: 'fas fa-folder',
        DEFAULT_CATEGORY_NAME: '默认分组',
        DEFAULT_CATEGORY_DESC: '未分类的收藏',
        DEFAULT_CATEGORY_COLOR: '#95a5a6',
        DEFAULT_CATEGORY_ICON: 'fas fa-inbox',
        ALL_CATEGORY_COLOR: '#6c757d',
        
        ICONS: [
            { value: 'fas fa-folder', label: '📂 文件夹' },
            { value: 'fas fa-briefcase', label: '💼 工作' },
            { value: 'fas fa-gamepad', label: '🎮 娱乐' },
            { value: 'fas fa-tools', label: '🔧 工具' },
            { value: 'fas fa-users', label: '👥 社交' },
            { value: 'fas fa-book', label: '📖 学习' },
            { value: 'fas fa-shopping-cart', label: '🛒 购物' },
            { value: 'fas fa-heart', label: '❤️ 收藏' }
        ]
    };

    constructor(apiService) {
        this.api = apiService;
        this.categories = [];
        this.currentEditCategoryId = null;
        // DOM 元素缓存
        this._domCache = {};
    }

    /**
     * 获取并缓存 DOM 元素
     */
    _getElement(id) {
        if (!this._domCache[id]) {
            this._domCache[id] = document.getElementById(id);
        }
        return this._domCache[id];
    }

    /**
     * 清除 DOM 缓存
     */
    _clearDomCache() {
        this._domCache = {};
    }

    /**
     * 统一的错误处理
     */
    _handleError(error, defaultMessage = '网络错误，请稍后重试') {
        console.error('操作出错:', error);
        showNotification(defaultMessage, 'error');
    }

    /**
     * 统一的 API 响应处理
     */
    _handleResponse(response, successMessage, errorMessage) {
        if (response.success) {
            if (successMessage) {
                showNotification(successMessage, 'success');
            }
            return response.data;
        } else {
            showNotification(response.message || errorMessage, 'error');
            return null;
        }
    }

    /**
     * 加载分组列表
     */
    async loadCategories() {
        try {
            const response = await this.api.getCategories();
            if (response.success) {
                this.categories = response.data.categories || [];
                console.log('分组数据加载成功:', this.categories.length, '个分组');
                return this.categories;
            } else {
                showNotification('加载分组失败', 'error');
                return [];
            }
        } catch (error) {
            this._handleError(error, '加载分组失败');
            return [];
        }
    }

    /**
     * 添加分组
     */
    async addCategory(name, description = '', color = null, icon = null) {
        if (!name?.trim()) {
            showNotification('请输入分组名称', 'error');
            return false;
        }

        try {
            const response = await this.api.createCategory(
                name.trim(),
                description.trim(),
                color || CategoryManager.CONSTANTS.DEFAULT_COLOR,
                icon || CategoryManager.CONSTANTS.DEFAULT_ICON
            );
            
            const data = this._handleResponse(response, '分组创建成功！', '分组创建失败');
            if (data) {
                this.categories.push(data.category);
                return data.category;
            }
            return false;
        } catch (error) {
            this._handleError(error, '创建分组失败');
            return false;
        }
    }

    /**
     * 更新分组
     */
    async updateCategory(id, data) {
        try {
            const response = await this.api.updateCategory(id, data);
            const result = this._handleResponse(response, '分组更新成功！', '分组更新失败');
            
            if (result) {
                const index = this.categories.findIndex(c => c.id === id);
                if (index !== -1) {
                    this.categories[index] = result.category;
                }
                return result.category;
            }
            return false;
        } catch (error) {
            this._handleError(error, '更新分组失败');
            return false;
        }
    }

    /**
     * 渲染分组选择器
     */
    renderCategorySelects() {
        const categorySelect = this._getElement('categorySelect');
        const categoryFilter = this._getElement('categoryFilter');

        if (categorySelect) {
            this._renderSelect(categorySelect, '选择分组...', false);
        }

        if (categoryFilter) {
            this._renderSelect(categoryFilter, '所有分组', true);
        }
    }

    /**
     * 辅助方法：渲染单个选择器
     */
    _renderSelect(element, placeholder, showCount) {
        const options = [
            `<option value="">${placeholder}</option>`,
            ...this.categories.map(category => {
                const count = showCount ? ` (${category.bookmark_count || 0})` : '';
                return `<option value="${category.id}">${escapeHtml(category.name)}${count}</option>`;
            })
        ];
        element.innerHTML = options.join('');
    }

    /**
     * 渲染分组标签栏
     */
    renderCategoriesBar(currentFilter = '') {
        const categoriesBar = this._getElement('categoriesBar');
        if (!categoriesBar || this.categories.length === 0) {
            if (categoriesBar) categoriesBar.innerHTML = '';
            return;
        }

        const totalCount = this._getTotalCount();
        const tags = [
            this._createAllTag(currentFilter, totalCount),
            ...this.categories.map(cat => this._createCategoryTag(cat, currentFilter))
        ];

        categoriesBar.innerHTML = '';
        tags.forEach(tag => categoriesBar.appendChild(tag));
    }

    /**
     * 获取真实的收藏总数
     */
    _getTotalCount() {
        // 始终使用 bookmarkManager 的实际书签数量，而不是分组统计之和
        // 因为分组统计可能漏掉未分组的书签
        if (typeof bookmarkManager !== 'undefined' && bookmarkManager) {
            return bookmarkManager.getCount();
        }
        // 如果 bookmarkManager 不可用，返回 0 而不是使用不准确的统计
        return 0;
    }

    /**
     * 创建"全部"标签
     */
    _createAllTag(currentFilter, totalCount) {
        const tag = document.createElement('div');
        tag.className = `category-tag ${currentFilter === '' ? 'active' : ''}`;
        tag.style.backgroundColor = CategoryManager.CONSTANTS.ALL_CATEGORY_COLOR;
        tag.innerHTML = `
            <i class="fas fa-th-large"></i>
            <span>全部</span>
            <span class="count">${totalCount}</span>
        `;
        tag.onclick = () => this._dispatchFilterChange('');
        return tag;
    }

    /**
     * 创建分组标签
     */
    _createCategoryTag(category, currentFilter) {
        const tag = document.createElement('div');
        const isActive = currentFilter === category.id.toString();
        tag.className = `category-tag ${isActive ? 'active' : ''}`;
        tag.style.backgroundColor = category.color;
        
        // 计算该分组的实际书签数量（从 bookmarkManager 获取准确数据）
        let actualCount = category.bookmark_count || 0;
        if (typeof bookmarkManager !== 'undefined' && bookmarkManager) {
            // 从实际书签列表中统计该分组的书签数量
            actualCount = bookmarkManager.bookmarks.filter(b => 
                b.category_id && b.category_id.toString() === category.id.toString()
            ).length;
        }
        
        tag.innerHTML = `
            <i class="${category.icon}"></i>
            <span>${escapeHtml(category.name)}</span>
            <span class="count">${actualCount}</span>
        `;
        tag.onclick = () => this._dispatchFilterChange(category.id);
        return tag;
    }

    /**
     * 触发分类筛选变化事件
     */
    _dispatchFilterChange(categoryId) {
        window.dispatchEvent(new CustomEvent('categoryFilterChange', {
            detail: { categoryId }
        }));
    }

    /**
     * 获取总收藏数
     */
    getTotalBookmarkCount() {
        return this.categories.reduce((sum, cat) => 
            sum + (parseInt(cat.bookmark_count) || 0), 0
        );
    }

    /**
     * 确保默认分组存在
     */
    async ensureDefaultCategory() {
        const defaultCategory = this._findDefaultCategory();

        if (!defaultCategory) {
            console.log('未找到默认分组，正在创建...');
            const { DEFAULT_CATEGORY_NAME, DEFAULT_CATEGORY_DESC, 
                    DEFAULT_CATEGORY_COLOR, DEFAULT_CATEGORY_ICON } = CategoryManager.CONSTANTS;
            
            const category = await this.addCategory(
                DEFAULT_CATEGORY_NAME,
                DEFAULT_CATEGORY_DESC,
                DEFAULT_CATEGORY_COLOR,
                DEFAULT_CATEGORY_ICON
            );
            
            if (category) {
                console.log('默认分组创建成功:', category);
                return category;
            }
        }

        return defaultCategory;
    }

    /**
     * 查找默认分组
     */
    _findDefaultCategory() {
        return this.categories.find(c => 
            c.name === CategoryManager.CONSTANTS.DEFAULT_CATEGORY_NAME
        );
    }

    /**
     * 获取默认分组ID
     */
    getDefaultCategoryId() {
        const defaultCategory = this._findDefaultCategory();
        return defaultCategory?.id || null;
    }

    /**
     * 显示分组管理对话框
     */
    showManagementDialog() {
        this.renderManagementDialog();
        const modal = this._getElement('categoryModal');
        if (modal) {
            modal.style.display = 'block';
        }
    }

    /**
     * 渲染分组管理对话框
     */
    renderManagementDialog() {
        let modal = this._getElement('categoryModal');
        if (!modal) {
            modal = this._createModal('categoryModal');
        }

        modal.innerHTML = this._getManagementDialogHTML();
        
        // 绑定事件
        const addBtn = document.getElementById('addCategoryBtn');
        if (addBtn) {
            addBtn.onclick = () => this.handleAddCategory();
        }
    }

    /**
     * 创建模态框
     */
    _createModal(id) {
        const modal = document.createElement('div');
        modal.id = id;
        modal.className = 'modal';
        document.body.appendChild(modal);
        this._domCache[id] = modal;
        return modal;
    }

    /**
     * 获取管理对话框 HTML
     */
    _getManagementDialogHTML() {
        return `
            <div class="modal-content category-modal">
                <div class="modal-header">
                    <h3><i class="fas fa-folder"></i> 管理分组</h3>
                    <button class="modal-close" onclick="document.getElementById('categoryModal').style.display='none'">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                <div class="modal-body">
                    ${this._getAddCategoryFormHTML()}
                    ${this._getCategoriesListHTML()}
                </div>
            </div>
        `;
    }

    /**
     * 获取添加分组表单 HTML
     */
    _getAddCategoryFormHTML() {
        const iconOptions = CategoryManager.CONSTANTS.ICONS
            .map(icon => `<option value="${icon.value}">${icon.label}</option>`)
            .join('');

        return `
            <div class="add-category-form">
                <h4>添加新分组</h4>
                <div class="form-row">
                    <input type="text" id="newCategoryName" placeholder="分组名称" maxlength="100">
                    <input type="color" id="newCategoryColor" value="${CategoryManager.CONSTANTS.DEFAULT_COLOR}" title="选择颜色">
                    <select id="newCategoryIcon" title="选择图标">
                        ${iconOptions}
                    </select>
                    <button id="addCategoryBtn" class="btn-primary">
                        <i class="fas fa-plus"></i> 添加
                    </button>
                </div>
                <input type="text" id="newCategoryDescription" placeholder="分组描述（可选）" maxlength="1000">
            </div>
        `;
    }

    /**
     * 获取分组列表 HTML
     */
    _getCategoriesListHTML() {
        return `
            <div class="categories-list">
                <h4>现有分组</h4>
                <div id="categoriesListContainer">
                    ${this.renderCategoriesList()}
                </div>
            </div>
        `;
    }

    /**
     * 渲染分组列表
     */
    renderCategoriesList() {
        if (this.categories.length === 0) {
            return '<p class="text-muted">还没有创建任何分组</p>';
        }

        return this.categories
            .map(category => this._getCategoryItemHTML(category))
            .join('');
    }

    /**
     * 获取单个分组项 HTML
     */
    _getCategoryItemHTML(category) {
        return `
            <div class="category-item">
                <div class="category-info">
                    <div class="category-icon" style="background-color: ${category.color}">
                        <i class="${category.icon}"></i>
                    </div>
                    <div class="category-details">
                        <h5>${escapeHtml(category.name)}</h5>
                        <p>${escapeHtml(category.description || '无描述')} • ${category.bookmark_count || 0} 个收藏</p>
                    </div>
                </div>
                <div class="category-actions">
                    <button class="btn-small btn-edit" onclick="categoryManager.showEditDialog(${category.id})">
                        <i class="fas fa-edit"></i> 编辑
                    </button>
                </div>
            </div>
        `;
    }

    /**
     * 处理添加分组
     */
    async handleAddCategory() {
        const formData = this._getFormData(['newCategoryName', 'newCategoryDescription', 
                                           'newCategoryColor', 'newCategoryIcon']);
        if (!formData) return;

        const { newCategoryName, newCategoryDescription, newCategoryColor, newCategoryIcon } = formData;
        
        const category = await this.addCategory(
            newCategoryName.value,
            newCategoryDescription.value,
            newCategoryColor.value,
            newCategoryIcon.value
        );

        if (category) {
            this._resetForm(formData);
            this._refreshUI();
        }
    }

    /**
     * 获取表单数据
     */
    _getFormData(fieldIds) {
        const data = {};
        for (const id of fieldIds) {
            const element = document.getElementById(id);
            if (!element) return null;
            data[id] = element;
        }
        return data;
    }

    /**
     * 重置表单
     */
    _resetForm(formData) {
        const { newCategoryName, newCategoryDescription, newCategoryColor, newCategoryIcon } = formData;
        newCategoryName.value = '';
        newCategoryDescription.value = '';
        newCategoryColor.value = CategoryManager.CONSTANTS.DEFAULT_COLOR;
        newCategoryIcon.value = CategoryManager.CONSTANTS.DEFAULT_ICON;
    }

    /**
     * 刷新 UI
     */
    _refreshUI() {
        this.renderManagementDialog();
        this.renderCategorySelects();
        window.dispatchEvent(new CustomEvent('categoriesUpdated'));
    }

    /**
     * 显示编辑对话框
     */
    showEditDialog(categoryId) {
        const category = this.getCategoryById(categoryId);
        if (!category) return;

        this.currentEditCategoryId = categoryId;

        let modal = this._getElement('editCategoryModal');
        if (!modal) {
            modal = this._createModal('editCategoryModal');
        }

        modal.innerHTML = this._getEditDialogHTML(category);
        modal.style.display = 'block';

        // 绑定事件
        const saveBtn = document.getElementById('saveEditCategoryBtn');
        if (saveBtn) {
            saveBtn.onclick = () => this.handleSaveEdit();
        }
    }

    /**
     * 获取编辑对话框 HTML
     */
    _getEditDialogHTML(category) {
        const iconOptions = CategoryManager.CONSTANTS.ICONS
            .map(icon => {
                const selected = category.icon === icon.value ? 'selected' : '';
                return `<option value="${icon.value}" ${selected}>${icon.label}</option>`;
            })
            .join('');

        return `
            <div class="modal-content">
                <div class="modal-header">
                    <h3><i class="fas fa-edit"></i> 编辑分组</h3>
                    <button class="modal-close" onclick="document.getElementById('editCategoryModal').style.display='none'">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <label>分组名称</label>
                        <input type="text" id="editCategoryName" value="${escapeHtml(category.name)}" maxlength="100">
                    </div>
                    <div class="form-group">
                        <label>分组描述</label>
                        <input type="text" id="editCategoryDescription" value="${escapeHtml(category.description || '')}" maxlength="1000">
                    </div>
                    <div class="form-row">
                        <div class="form-group">
                            <label>颜色</label>
                            <input type="color" id="editCategoryColor" value="${category.color}">
                        </div>
                        <div class="form-group">
                            <label>图标</label>
                            <select id="editCategoryIcon">
                                ${iconOptions}
                            </select>
                        </div>
                    </div>
                    <div class="modal-buttons">
                        <button id="saveEditCategoryBtn" class="btn-primary">保存</button>
                        <button onclick="document.getElementById('editCategoryModal').style.display='none'" class="btn-secondary">取消</button>
                    </div>
                </div>
            </div>
        `;
    }

    /**
     * 处理保存编辑
     */
    async handleSaveEdit() {
        if (!this.currentEditCategoryId) return;

        const formData = this._getFormData(['editCategoryName', 'editCategoryDescription',
                                           'editCategoryColor', 'editCategoryIcon']);
        if (!formData) return;

        const { editCategoryName, editCategoryDescription, editCategoryColor, editCategoryIcon } = formData;

        const data = {
            name: editCategoryName.value.trim(),
            description: editCategoryDescription.value.trim(),
            color: editCategoryColor.value,
            icon: editCategoryIcon.value
        };

        const category = await this.updateCategory(this.currentEditCategoryId, data);
        if (category) {
            const modal = this._getElement('editCategoryModal');
            if (modal) modal.style.display = 'none';
            
            this.currentEditCategoryId = null;
            this._refreshUI();
        }
    }

    /**
     * 根据ID获取分组
     */
    getCategoryById(id) {
        return this.categories.find(c => c.id === id);
    }
}

// 导出供其他模块使用
if (typeof module !== 'undefined' && module.exports) {
    module.exports = CategoryManager;
}
